package com.hdjk.view.dialog;

import android.app.ActivityManager;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.hdjk.view.R;
import com.hdjk.view.config.Constant;
import com.hdjk.view.service.UpdateVersionService;
import com.lst.projectlib.util.DensityUtil;

import java.io.File;
import java.util.List;

/**
 * Created by Administrator on 2017/8/14.
 */

public class UpdateDialog extends Dialog implements View.OnClickListener{
    private Context mContext = null;
    private UpdateDialogListener mClickListener = null;
    private TextView tv_title = null;
    private TextView tv_content = null;
    private Button btn_cancel = null;
    private Button btn_ok = null;
    private View vLineV = null;
    private String link = "";
    private Intent updateIntent = null;

    public interface UpdateDialogListener {
        void onCancel();
        void onOk();
    }

    public UpdateDialog(Context context, UpdateDialogListener listener) {
        super(context, R.style.progress_dialog);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mContext = context;
        mClickListener = listener;

        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.INTENT_FILTER_STRING_UPDATE_APK_FINISH);
        mContext.registerReceiver(mReceiver, filter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.dialog_update);

        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_content = (TextView) findViewById(R.id.tv_content);
        btn_cancel = (Button) findViewById(R.id.btn_cancel);
        btn_cancel.setOnClickListener(this);
        btn_ok = (Button) findViewById(R.id.btn_ok);
        btn_ok.setOnClickListener(this);

        vLineV = findViewById(R.id.vLineV);

        WindowManager windowManager = (WindowManager) this.getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(dm);

        getWindow().getAttributes().width = dm.widthPixels - DensityUtil.dip2px(this.getContext(), 60);
        getWindow().getAttributes().dimAmount = 0.3f;
//        getWindow().getAttributes().y = -dm.heightPixels * 1 / 10;

        this.setCancelable(false);
        this.setCanceledOnTouchOutside(false);
    }

    public void showDialog(String info, final String isForced, final String link, String title) {
        this.show();

        this.link = link;

        if (tv_title != null) {
            tv_title.setText(title);
        }
        if (tv_content != null) {
            tv_content.setText(info);
        }

        if(isForced.equalsIgnoreCase("true")){
            // 如果是强制更新，则没有取消按钮
            if (btn_cancel != null ) {
                vLineV.setVisibility(View.GONE);
                btn_cancel.setVisibility(View.GONE);
            }
        }else{
            if (btn_cancel != null ) {
                vLineV.setVisibility(View.VISIBLE);
                btn_cancel.setVisibility(View.VISIBLE);
            }
        }
    }

    private boolean isServiceRunning() {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(30);
        if (serviceList==null || serviceList.size() <= 0) {
            return isRunning;
        }
        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals("com.hdjk.view.service.UpdateVersionService")) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                return;
            }

            if(Constant.INTENT_FILTER_STRING_UPDATE_APK_FINISH.equals(intent.getAction())){//下载最新apk完成
                if(btn_ok!=null){
                    String progress=intent.getStringExtra("progress");
                    boolean isSuccess = intent.getBooleanExtra("is_success", false);

                    if(TextUtils.isEmpty(progress)){
                        if (isSuccess) {
                            btn_ok.setText("安装");
                            btn_ok.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    try {
                                        Intent installIntent = new Intent(Intent.ACTION_VIEW);
                                        installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        Uri apkUri;

                                        File updateFile = new File(new File(Environment.getExternalStorageDirectory(),
                                                Constant.downLoadPath).getPath(), mContext.getResources()
                                                .getString(R.string.app_name) + ".apk");
                                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                            //判读版本是否在7.0以上
                                            apkUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", updateFile);
                                            //添加这一句表示对目标应用临时授权该Uri所代表的文件
                                            installIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                        } else {
                                            apkUri = Uri.fromFile(updateFile);
                                        }
                                        installIntent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                                        mContext.startActivity(installIntent);
                                    } catch (Exception e) {
                                    }
                                }
                            });
                        } else {
                            btn_ok.setText("更新");
                        }

                    }else{
                        btn_ok.setText("已下载"+progress);
                    }
                }
            }
        }
    };

    public void onDestroy() {
        if (mReceiver != null) {
            mContext.unregisterReceiver(mReceiver);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_cancel:
                this.cancel();

                if (mClickListener != null) {
                    mClickListener.onCancel();
                }
                break;
            case R.id.btn_ok:
                if(isServiceRunning()){

                }else{
                    // 开启更新服务UpdateService
                    updateIntent = new Intent(mContext, UpdateVersionService.class);
                    updateIntent.putExtra("url", link);
                    mContext.startService(updateIntent);

                    if (mClickListener != null) {
                        mClickListener.onOk();
                    }
                }
                break;
        }
    }
}
